<?php
/**
 * The Database Interface
 *
 **/

class PDO_DbWrapper {
  var $db;
  var $db_index;
  function PDO_DbWrapper($db_index='default') {
    // XXX this stuff should really be in an openConn function
    $pre = $GLOBALS['PRIFAKX'];
    // XXX this needs to be fixed to handle host
    $db_name = $GLOBALS["${pre}DB"][$db_index]['driver'].':'.$GLOBALS["${pre}DB"][$db_index]['uri'];
    $db_user = $GLOBALS["${pre}DB"][$db_index]['uname'];
    $db_pass = $GLOBALS["${pre}DB"][$db_index]['upass'];
    $db_options = array();
    //$db_options = array( PDO::ATTR_PERSISTENT => true );

    $this->db = new PDO($db_name, $db_user, $db_pass, $db_options);
    // XXX remove this for production. We need switches for these things. in dbinfo.ini
    $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
  }

  function exec( $estr ) {
    $GLOBALS["${GLOBALS['PRIFAKX']}DB"][$db_index]['EXEC_CALL'][] = $estr;
    try {
      return $this->db->exec($estr);
    } catch ( PDOException $e ) {
      print "ERROR: " . $e->getMessage() . "<br />";
      die();
    }
  }
  // XXX $type is currently ignored.
  function query( $qstr, $type='ASSOC' ) {
    $GLOBALS["${GLOBALS['PRIFAKX']}DB"][$db_index]['QUERY_CALL'][] = $qstr;
    try {
      $res = $this->db->query($qstr);
      $data = $res->fetch(PDO::FETCH_ASSOC);
      $res = NULL;
      return $data;
    } catch ( PDOException $e ) {
      print "ERROR: " . $e->getMessage() . "<br />";
      die();
    }
  }
  function quoteArr( ) {
    $end = func_num_args();
    $argv = func_get_args();
    for($i=0; $i < $end; ++$i) 
      $argv[$i] = $this->db->quote($argv[$i]);
    return $argv;
  }
  function quote( $object ) {
    return $this->db->quote($object);
  }

  function closeConn( ) {
    $this->db = null;
  }
}

function dbOpenConn($db='default') {
  $pre = $GLOBALS['PRIFAKX'];
  if( $GLOBALS["${pre}DB_CONN"][$db] )
    return $GLOBALS["${pre}DB_CONN"][$db];
  else {
    $db_wrapper = $GLOBALS["${pre}DB"][$db]['wrapper'];
    return $GLOBALS["${pre}DB_CONN"][$db] = new $db_wrapper($db); 
  }
}
function dbCloseConn($db='default') {
  $GLOBALS["${GLOBALS['PRIFAKX']}DB_CONN"][$db]->closeConn();
  $GLOBALS["${GLOBALS['PRIFAKX']}DB_CONN"][$db] = null;
}

?>
